'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require('underscore');
const utils = require('./userGroupFunction');
const operationRecord = require("../sys/operationRecordAction");

module.exports = async function (params) {
    /*
    * childrenMenuArr 前端树形结构中被选中节点id
    * parentMenuArr 都为半选中的父级节点id。该数据不存库 目的为方便数据库查询出用户权限分类
    * 如果只查询出子节点为查询出父级节点无法进行权限分类
    * */
    let childrenMenuArr = params.childrenMenuArr,
        parentMenuArr = params.parentMenuArr,
        allMenuArrId = [].concat(childrenMenuArr, parentMenuArr),
        menuArrStr = childrenMenuArr.join(','),
        insertSql = 'UPDATE user_group SET  ? WHERE group_id = ?',
        getSysMenuSql = `SELECT sm.* ,
                        r.path,
                        r.is_first,
                        r.redirect,
                        r.url 
                        FROM sys_menu sm 
                        LEFT JOIN 
                        router r 
                        ON r.menu_id=sm.menu_id WHERE sm.menu_id IN (?);`;
    let allMenuArr = [];
    if (allMenuArrId.length > 0) {
        allMenuArr = await conn(getSysMenuSql, [allMenuArrId])
    }
    let userGroupAuth = utils.getUserGroupAuth(allMenuArr);//查询出权限下所有菜单后 进行权限计算 获取出该用户所在用户组中的菜单 以及路由权限
    await conn(insertSql, [{
        menus: menuArrStr,
        menu: userGroupAuth.menuList,
        routes: userGroupAuth.routeList
    }, params.groupId]);
    await operationRecord(params);
    return {success: true};
};
